package com.dd.shop4j.common.utils.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dd.shop4j.common.utils.interceptor.form.FormToken;
import com.dd.shop4j.common.utils.interceptor.form.IFormTokenManager;

/**
 * 防止表单重复提交 拦截器
 * 
 * @author tangshu
 * 
 */
public class FormSubmitInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = Logger.getLogger(FormSubmitInterceptor.class);

	//formtoken的过期时间 默认10分钟
	private static final long formTokenTimeOut = 600000;
	
	//表单令牌管理器
	private IFormTokenManager formTokenManager;
	
	public void setFormTokenManager(IFormTokenManager formTokenManager) {
		this.formTokenManager = formTokenManager;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//得到页面提交的token令牌
		String token = request.getParameter(FormToken.FORM_UNIQ_FIELD_NAME);
		if (StringUtils.isNotEmpty(token)) {
			logger.debug("form token -> " + token);
			//如果验证通过，清空token
			if (formTokenManager.validateFormToken(request, token)) {
				formTokenManager.destoryFormToken(request);
			} else {
				throw new Exception("对不起，当前会话已过期");
			}
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		FormToken formToken = formTokenManager.getFormToken(request);
		//如果没有设置过formtoken 或者 formtoken已经过期  那么 重新初始化formtoken
		if (formToken == null || 
				System.currentTimeMillis() - formToken.getCreateTime() >= formTokenTimeOut) {
			formTokenManager.initFormToken(request);
			logger.debug("init the form token");
		}
		super.postHandle(request, response, handler, modelAndView);
	}

}
